package com.example.fence;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.fence.entity.MyMqttClient;
import com.example.fence.util.HttpClientUtil;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;

import java.math.BigInteger;
import java.util.*;

import static com.example.fence.entity.MyMqttClient.*;
import static com.example.fence.init.DeviceUtil.SNtoUUID;
import static com.example.fence.util.FenceDetectUtil.PoiInPoly;
import static com.example.fence.util.FenceStoreUtil.imeiToPointList;

@Slf4j
public  class Task {

    public static MqttClient mqtt = MyMqttClient.createMqtt();

    public static String TBtopic = "v1/devices/me/telemetry";



    public static boolean decoderTask(String topic, String MyData){
        try{
            String IMEI=topic.substring(5,topic.length()-3);
            //前四位项目号
            if(topic.charAt(4)=='/'){
                if(MyData.length()>50){
                    MyData = MyData.substring(44, MyData.length() - 6);
                }
                //B1帧
                if(topic.contains("B1")){
                    int L = Integer.parseInt(MyData.substring(54,56),16);
                    int M = Integer.parseInt(MyData.substring(56+4*L,58+4*L),16);
                    int N = Integer.parseInt(MyData.substring(58+4*L+2*M,60+4*L+2*M),16);
                    int P = Integer.parseInt(MyData.substring(60+4*L+2*M+2*N,62+4*L+2*M+2*N),16);
                    //lon
                    String lon = MyData.substring(110+4*L+2*M+2*N+2*P,130+4*L+2*M+2*N+2*P);
                    StringBuilder sb_lon = new StringBuilder();
                    for (int i = 0; i < lon.length(); i += 2) {
                        String str_lon = lon.substring(i, i + 2);
                        sb_lon.append((char) Integer.parseInt(str_lon, 16));
                    }
                    lon = sb_lon.toString();
                    //lat
                    String lat = MyData.substring(92+4*L+2*M+2*N+2*P,110+4*L+2*M+2*N+2*P);
                    StringBuilder sb_lat = new StringBuilder();
                    for (int i = 0; i < lat.length(); i += 2) {
                        String str_lat = lat.substring(i, i + 2);
                        sb_lat.append((char) Integer.parseInt(str_lat, 16));
                    }
                    lat = sb_lat.toString();
                    String point=lon+","+lat;
//                    //测试用
//                    String point="120.158917,30.29928";
                    boolean result = PoiInPoly(imeiToPointList.get(IMEI), point);
                    if(result){
                        log.info("YES-IMEI：{} 点：{} 在地图范围内",IMEI,point);
                        return true ;
                    }
                    else {

                        log.info("NO-IMEI：{} 点：{} 在地图范围外",IMEI,point);
                        return false ;
                    }
                }
            }
        } catch(Exception ex) {
            ex.printStackTrace();

        }
        return false;
    }
    public static void PostC2(String topic){
        //发送帧C2
        String header = "EB900002C20001";
        String data="";
        String IMEI=topic.substring(5,topic.length()-3);
        String ProjectNumber=topic.substring(0,4);
        System.out.println(ProjectNumber);
        StringBuilder sb1 = new StringBuilder();
        for (int i = 0; i < IMEI.length(); i++) {
            sb1.append('3');
            sb1.append(IMEI.charAt(i));
        }
        String RE_IMEI = sb1.toString();
        if(topic.contains("BS53")){
             data ="0101";
        }
        else  data ="0101010000000000";
        String tail ="FE";
        String message = header+RE_IMEI+data;
        message =message+calculateCRC16(message)+tail;
        System.out.println(message);
        String topic_send = ProjectNumber+"/"+IMEI+"/C2";
        publishMessageHex(message, topic_send, mqtt);
    }
    public static void PostUnC2(String IMEI){
        String token= HttpClientUtil.get_token("http://47.92.164.101:28080/api/auth/login","tenant@thingsboard.org","tenant")[0];
        String DeviceID=SNtoUUID.get(IMEI);
        String data="";
        // String DeviceID="9dd39c20-6e64-11ee-abb8-e960d73f3051";
        String url="http://47.92.164.101:28080/api/device/info/"+DeviceID;
        String[] resultStr= HttpClientUtil.get_data(url,token);//String 格式获取结果, [0]为statusCode，[1]为结果(结果可能不是json)
        //发送帧C2
        String header = "EB900002C20001";
        if(Integer.valueOf(resultStr[0])==200) {
            //获取设备列表
            JSONObject jsonResult = JSONObject.parseObject(resultStr[1]);
            String ProjectNumber = jsonResult.getString("customerTitle");
            System.out.println(ProjectNumber);
            StringBuilder sb1 = new StringBuilder();
            for (int i = 0; i < IMEI.length(); i++) {
                sb1.append('3');
                sb1.append(IMEI.charAt(i));
            }
            String RE_IMEI = sb1.toString();
            if(ProjectNumber.contains("BS53")){
                data ="0101";
            }
            else data ="0100000000000000";
            String tail ="FE";
            String message = header+RE_IMEI+data;
            message =message+calculateCRC16(message)+tail;
            System.out.println(message);
            String topic_send = ProjectNumber+"/"+IMEI+"/C2";
            publishMessageHex(message, topic_send, mqtt);
        }
    }
    public static void main(String[] args){
        PostUnC2("860987052079693");
    }

    public static String calculateCRC16(String hexString) {
        byte[] data = new BigInteger(hexString, 16).toByteArray();
        if (data[0] == 0) {
            data = Arrays.copyOfRange(data, 1, data.length);
        }
        int crc = 0xFFFF;
        for (byte b : data) {
            crc ^= b & 0xFF;
            for (int i = 0; i < 8; i++) {
                if ((crc & 0x0001) != 0) {
                    crc >>= 1;
                    crc ^= 0xA001;
                } else {
                    crc >>= 1;
                }
            }
        }
        byte crcHigh = (byte) ((crc >> 8) & 0xFF);
        byte crcLow = (byte) (crc & 0xFF);
        String cHigh= String.format("%02X", crcHigh);
        String clow= String.format("%02X", crcLow);
        hexString = cHigh+clow;
        return hexString;
    }
    public static void PostFence(String IMEI, List<String> fence) throws MqttException {
        Map<String, String> map = new HashMap<>();
        map.put("fence", "N"+fence);
        map.put("Delete", "N0");
        Gson gson = new Gson();
        MqttClient mqttForTB = createMqttForTB(IMEI);
        String TBmessage = gson.toJson(map);
        publishMessage(TBmessage, TBtopic, mqttForTB);
        mqttForTB.disconnect();
        mqttForTB.close();
        log.info("发送线程PostB1已经断开: "+IMEI);
    }
    public static void PostAlarm(String IMEI, Set<Integer> WarnType, Set<String> ReciveBox, String SendBox,int sendInterval) throws MqttException {
        Map<String, String> map = new HashMap<>();
        map.put("SendBox", "N"+SendBox);
        map.put("WarnType", "N"+WarnType);
        map.put("ReciveBox", "N"+ReciveBox);
        map.put("sendInterval", "N"+sendInterval);
        Gson gson = new Gson();
        MqttClient mqttForTB = createMqttForTB(IMEI);
        String TBmessage = gson.toJson(map);
        publishMessage(TBmessage, TBtopic, mqttForTB);
        mqttForTB.disconnect();
        mqttForTB.close();
        log.info("发送线程PostB1已经断开: "+IMEI);
    }
    public static void PostDelete(String IMEI) throws MqttException {
        Map<String, String> map = new HashMap<>();
        map.put("Delete", "N1");
        Gson gson = new Gson();
        MqttClient mqttForTB = createMqttForTB(IMEI);
        String TBmessage = gson.toJson(map);
        publishMessage(TBmessage, TBtopic, mqttForTB);
        mqttForTB.disconnect();
        mqttForTB.close();
        log.info("发送线程PostB1已经断开: "+IMEI);
    }



}
